package com.fwtai.controller;

import com.fwtai.service.ApiService;
import com.fwtai.tool.ToolClient;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class ApiController{

  private final ApiService apiService;

  public ApiController(final ApiService apiService){
    this.apiService = apiService;
  }

  @GetMapping("/page")
  public void page(final HttpServletResponse response) throws IOException{
    response.setStatus(302);
    final int device_id = 39630237;
    response.sendRedirect("https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id="+apiService.getClientId()+"&redirect_uri=oob&scope=basic,netdisk&device_id="+device_id);
  }

  @GetMapping("/getAccessToken") // http://127.0.0.1:5512/api/getAccessToken?code=8ea2bcb8e041c2983d18e671130410be
  public void getAccessToken(final String code,final HttpServletResponse response){
    if(code == null || code.length() == 0){
      ToolClient.responseJson(ToolClient.createJson(199,"请输入code",null),response);
      return;
    }
    final int rows = apiService.getAccessToken(code);
    if(rows > 0){
      ToolClient.responseJson(ToolClient.createJson(200,"操作成功",rows),response);
    }else {
      ToolClient.responseJson(ToolClient.createJson(199,"操作失败",null),response);
    }
  }

  @GetMapping("/refreshToken") // http://127.0.0.1:5512/api/refreshToken
  public void refreshToken(final HttpServletResponse response){
    final int rows = apiService.refreshToken(39630237);//应用名称:文件备份
    if(rows > 0){
      ToolClient.responseJson(ToolClient.createJson(200,"操作成功",rows),response);
    }else {
      ToolClient.responseJson(ToolClient.createJson(199,"操作失败",null),response);
    }
  }

  @PostMapping("/getInfo")
  public void getInfo(final Integer kid,final HttpServletResponse response){
    ToolClient.responseJson(apiService.getInfo(kid),response);
  }
}